package cn.islu.controller;

import cn.islu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/Login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object[] params = {req.getParameter("username"), req.getParameter("password"), req.getParameter("remember")};
        int Result = new UserServiceImpl().LoginUser(params);
        if (Result == 1) {
            HttpSession session = req.getSession(true);
            session.setMaxInactiveInterval(60 * 60 * 24 * 30);
            session.setAttribute("susername", req.getParameter("username"));
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60 * 60 * 24 * 30);
            resp.addCookie(cookie);
            resp.sendRedirect("Index");
        } else if (Result == 2) {
            HttpSession session = req.getSession(true);
            session.setMaxInactiveInterval(1);
            session.setAttribute("susername", req.getParameter("username"));
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(1);
            resp.addCookie(cookie);
            resp.sendRedirect("Index");
        } else if (Result == 0) {
            resp.getWriter().append("<script>\n" +
                    "alert(\"该账户未注册，请注册后重试\")\n" +
                    "window.location.href = \"/jsp/register.jsp\"" +
                    "</script>");
        } else {
            resp.getWriter().append("<script>\n" +
                    "alert(\"密码输入错误,请重新尝试\")\n" +
                    "window.location.href = \"/jsp/login.jsp\"" +
                    "</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
